package it.sisiper.mysight;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.widget.Toast;

/**
 * Activity containing the Option Menu, responsible of storing settings in the system user preferences
 * 
 * @author Federico Lancerin 1057505
 *
 */

public class OptionMenu extends PreferenceActivity {

	private SharedPreferences pref = null;
	Preference QrDecoder = null;
	Preference editableAddress = null;
	Toast success = null;
	Toast promptUser = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);

		success = Toast.makeText(this,
				"correctly read and set new server address", Toast.LENGTH_LONG);

		editableAddress = findPreference("serverAddress");
		QrDecoder = findPreference("qrCode");
		QrDecoder.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {	
				try {
					Intent intent = new Intent("com.google.zxing.client.android.SCAN");
					intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
					startActivityForResult(intent, 0);
				} catch (Exception e) {
					Intent goToMarket = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("market://details?id=com.google.zxing.client.android"));
					startActivity(goToMarket);
					return false;
				}				 
				return true;
			}
		});
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == 0) {
			if (resultCode == RESULT_OK) {
				String contents = intent.getStringExtra("SCAN_RESULT");
				editableAddress.getEditor()
						.putString("serverAddress", contents).apply();
				success.show();
				finish();
			}
		}
	}
}
